package cn.butcher21.view;

import cn.butcher21.dao.SaleDao;
import cn.butcher21.pojo.Sale;
import cn.butcher21.pojo.SaleData;
import cn.butcher21.utils.MakeTradeId;
import cn.butcher21.utils.Pay;
import cn.butcher21.window.CashWindow;
import cn.butcher21.window.CusPayWindow;
import cn.butcher21.window.WeScanWindow;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SaleController {

    @FXML
    private TableView<SaleData> saleTable;

    @FXML
    private Button cashBtn;

    @FXML
    private Button custScanBtn;

    @FXML
    private Button gunBtn;

    @FXML
    private TextField total;

    @FXML
    private TableColumn<SaleData, String> s_id;

    @FXML
    private TableColumn<SaleData, String> s_name;

    @FXML
    private TableColumn<SaleData, Double> s_price;

    @FXML
    private TableColumn<SaleData, Integer> s_count;

    @FXML
    private TableColumn<SaleData, Double> s_total;

    @FXML
    private Label cashier;

    @FXML
    private Label saleTips;

    @FXML
    private TextField scanId;

    LoginController login = (LoginController) Context.rootController.get(LoginController.class.getSimpleName());

    // 订单编号
    public String sId = "";
    //存入数据库的销售表的数据
    public List<Sale> salesToDB = new ArrayList<Sale>();

    public void loadSaleTableData() {
        // 更新表格数据
        ObservableList<SaleData> saleData = FXCollections.observableArrayList();
        for (SaleData s : saleDatas) {
            saleData.add(s);
        }
        s_id.setCellValueFactory(new PropertyValueFactory<SaleData, String>("id"));
        s_name.setCellValueFactory(new PropertyValueFactory<SaleData, String>("name"));
        s_count.setCellValueFactory(new PropertyValueFactory<SaleData, Integer>("count"));
        s_price.setCellValueFactory(new PropertyValueFactory<SaleData, Double>("price"));
        s_total.setCellValueFactory(new PropertyValueFactory<SaleData, Double>("total"));
        saleTable.setItems(saleData);
    }

    @FXML
    void initialize() {
        Context.rootController.put(this.getClass().getSimpleName(), this);
        //启动一个线程监听销售有无商品编号输入
        Thread t_saleScan = new Thread(new Runnable() {
            SaleDao saleDao = new SaleDao();
            int i = 0;
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String msg = scanId.getText();
                    if (msg.equals("")) {
                        System.out.println("监听中" + (++i) + "---无商品，当前商品数量" + saleDatas.size());
                        // 没有商品
                    } else {
                        // 有商品输入
                        if (saleDao.check(msg)) {
                            try {
                                SaleData saleData = saleDao.getSale(msg);
                                Sale sale = new Sale();
                                sale.setGid(saleData.getId());
                                sale.setCount(saleData.getCount());
                                if (sId.equals("")) {
                                    sId = MakeTradeId.get();
                                }
                                sale.setSid(sId);
                                sale.setSaleMan(login.getUsername().getText());
                                if (saleData.getId() != null) {
                                    saleDatas.add(saleData);
                                    salesToDB.add(sale);
                                    loadSaleTableData();
                                    scanId.setText("");
                                    double sum = 0;
                                    for (SaleData data : saleDatas) {
                                        sum += data.getTotal();
                                    }
                                    total.setText(String.valueOf(sum));
                                }
                            } catch (SQLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }
                        } else {
                            saleTips.setText("此商品无货");
                        }
                        System.out.println("监听中" + (++i) + "---有商品，当前商品数量" + saleDatas.size());
                    }
                }
            }
        });
        t_saleScan.start();
    }

    @FXML

    public List<SaleData> saleDatas = new ArrayList<SaleData>(); // 显示在销售表的数据

    public double sum = 0;

    @FXML
    void payByCash(ActionEvent event) throws Exception {
        if (!total.getText().equals("")) {
            sum = Double.parseDouble(total.getText());
            new CashWindow();

        }
    }


    @FXML
    void payByCustScan(ActionEvent event) throws IOException, InterruptedException {
        sum = Double.parseDouble(total.getText());
        sId = MakeTradeId.get(); // 获取订单编号
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Pay pay = new Pay();
                pay.cusScan(sId, total.getText(), login.getUsername().getText());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            CusPayWindow cusPayWindow = new CusPayWindow();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        t1.start();
        t1.join();
        t2.start();
    }

    @FXML
    void payBygunScan(ActionEvent event) throws Exception {
        new WeScanWindow();
    }

    @FXML
    public void revoke(ActionEvent event) {
        SaleData item = saleTable.getSelectionModel().getSelectedItem();
        saleTips.setText("将删除" + item.getId());
        saleDatas.remove(item);
        loadSaleTableData();
        double sum = 0;
        for (SaleData data : saleDatas) {
            sum += data.getTotal();
        }
        total.setText(String.valueOf(sum));
    }

    public TextField getTotal() {
        return total;
    }
}
